<?php

namespace App\Utils;

use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;

class ExcelUtils
{
    function createExcel($filePath)
    {
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load($filePath); // 加载Excel文件
        $worksheet = $spreadsheet->getActiveSheet();
        $hightestRow = $worksheet->getHighestRow();  //获取总行数
        $hightColumn = $worksheet->getHighestColumn(); // 获取总列数
        $data = array();
        for ($row = 1; $row <= $hightestRow; $row++) { //行号从1开始
            $info = array();
            for ($colum = 'A'; $colum < $hightColumn; $colum++) { //列数是以A列开始
                $item = $worksheet->getCell($colum . $row)->getValue();
                array_push($info, $item);
            }
            array_push($data, $info);
        }
        return $data;
    }
    // 导出数据
    function exportExcel($filePath, $data)
    {
        $spreadsheet = new Spreadsheet(); // 创建一个新的Excel对象
        $spreadsheet->getActiveSheet()->fromArray($data); // 将数据写入Excel
        $writer = new Xlsx($spreadsheet); // 创建一个XLSX写入器
        $writer->save($filePath); // 保存Excel文件
    }
}
